﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UDataBaseWork;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.DTO;
using XF.Meeting.IDal;

namespace XF.Meeting.DAL
{
    public class ExchangeToDbDal : BaseDAL, IExchangeToDbDal
    {
        public Task<(bool, int)> Insert(EmailEntity item, out string s)
        {
            if (item.CRoomIDs != "" && item.CRoomIDs != null)
            {
                string[] arrStr = item.CRoomIDs.Split(',');//按逗号截取  
                                                           //第一个为主会议室

                item.CRoomID = Convert.ToInt32(arrStr[0]);
                ArrayList list = new ArrayList(arrStr);
                list.RemoveAt(0);
                item.CRoomIDs = string.Join(",", (string[])list.ToArray(typeof(string)));
            }
            bool bResult = true;
            SqlParameter[] sqlParametersmeet = new SqlParameter[] {
                        new SqlParameter("@CRoomID",item.CRoomID),
                        new SqlParameter("@CRoomIDs",item.CRoomIDs),
                        new SqlParameter("@PassWords",""),
                        new SqlParameter("@CreateDate",DateTime.Today),
                        new SqlParameter("@ParticipantIDs",item.ParticipantIDs==null?"":item.ParticipantIDs),
                        new SqlParameter("@CreatorID",item.CreateID),
                        new SqlParameter("@ConferenceTheme",item.Subject==null?"":item.Subject),
                        new SqlParameter("@BeginTime",item.Start),
                        new SqlParameter("@EndTime",item.End),
                        new SqlParameter("@TimeLength",item.timelength),
                        new SqlParameter("@Coordinator",item.CreateID),
                        new SqlParameter("@HostPerson",item.CreateID),
                        new SqlParameter("@MinutesPerson",item.CreateID),
                        new SqlParameter("@GroupIDs",""),
                        new SqlParameter("@Outsiders",""),
                        new SqlParameter("@ConferenceRemark",item.Body==null?"":item.Body),
                        new SqlParameter("@State",item.state),
                          new SqlParameter("@IsSignIn","0"),
                        new SqlParameter("@CycleMeetType",item.CycleMeetType),
                        new SqlParameter("@CycleMeetGuid",item.CycleMeetGuid),
                        new SqlParameter("@ConferenceType",1),
                        new SqlParameter("@StrategyState",1),
                        new SqlParameter("@ToDayEnd",item.End.Date.AddDays(1)),
                        new SqlParameter("@IsPushEntWechat",false),
                        new SqlParameter("@ExchangeItemId",item.ID),
                         new SqlParameter("@sourceType",item.SourceType),
                         new SqlParameter("@ItemSort",item.sort),
                         new SqlParameter("@MasterItemId",item.itemId),

                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);
            if (item.CycleMeetType == 5 || item.CycleMeetType == 6 || item.CycleMeetType == 7 || item.CycleMeetType == 8)
            {
                if (!_db.ExcuteByTransaction(parasmeet, "spInsertConferenceInfo", out int ReturnValue, out string strError))
                {
                    bResult = false;
                    s = string.Format("DBProvider spInsertConferenceInfo EXECUTE_DB Error:{0}", strError);
                }
                else
                {
                    s = string.Empty;
                }
                return Task.FromResult((bResult, ReturnValue));
            }
            else
            {
                if (!_db.ExcuteByTransaction(parasmeet, "spInsertConferenceInfo", out int ReturnValue, out string strError))
                {
                    bResult = false;
                    s = string.Format("DBProvider spInsertConferenceInfo EXECUTE_DB Error:{0}", strError);
                }
                else
                {
                    s = string.Empty;
                }
                return Task.FromResult((bResult, ReturnValue));
            }

        }


        public Task<DataTable> GetAllO365Config(out string strError)
        {
            SqlParameter[] sqlParameters = new SqlParameter[] {

                };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spGetAllO365Config", out DataSet ds, out strError))
            {
                strError = string.Format("DBProvider spGetAllO365Config EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                strError = string.Empty;
            }
            return Task.FromResult(ds.Tables[0]);
        }

        public void InsertTemp(EmailEntity item, out string s)
        {
            if (item.CRoomIDs != "" && item.CRoomIDs != null)
            {
                string[] arrStr = item.CRoomIDs.Split(',');//按逗号截取  
                                                           //第一个为主会议室

                item.CRoomID = Convert.ToInt32(arrStr[0]);
                ArrayList list = new ArrayList(arrStr);
                list.RemoveAt(0);
                item.CRoomIDs = string.Join(",", (string[])list.ToArray(typeof(string)));
            }
            bool bResult = true;
            SqlParameter[] sqlParametersmeet = new SqlParameter[] {
                        new SqlParameter("@CRoomID",item.CRoomID),
                        new SqlParameter("@CreatorID",item.CreateID),//***
                        new SqlParameter("@ConferenceTheme",item.Subject==null?"":item.Subject),
                        new SqlParameter("@BeginTime",item.Start),
                        new SqlParameter("@EndTime",item.End),
                        new SqlParameter("@ExchangeItemId",item.ID),
                         new SqlParameter("@sourceType",item.SourceType),
                         new SqlParameter("@ItemSort",item.sort),
                         new SqlParameter("@MasterItemId",item.itemId+item.sort),
                         new SqlParameter("@IsSuccess",true),
                         new SqlParameter("@MeetType",item.CycleMeetType)
                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);

            if (!_db.ExcuteByTransaction(parasmeet, "spInsertExchangeTemp", out string strError))
            {
                bResult = false;
                s = string.Format("DBProvider spInsertConferenceInfo EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                s = string.Empty;
            }

        }
        public bool CheckIsCreated(EmailEntity meet)
        {
            int ID = 0;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@ExchangeItemId",meet.ID),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spCheckIsCreated", out DataSet ds, out string strError))
            {
                strError = string.Format("DBProvider spCheckIsCreated EXECUTE_DB Error:{0}", strError);
            }
            var IDList = TableToList_E.ToList<UserID>(ds.Tables[0]);
            if (IDList.Count > 0 && IDList != null)
            {
                ID = IDList[0].ID;
            }
            return ID > 0;
        }
        public bool CheckIsCreatedForZhouqi(EmailEntity meet)
        {
            int ID = 0;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@ExchangeItemId",meet.ID),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spCheckIsCreatedForZhouqi", out DataSet ds, out string strError))
            {
                strError = string.Format("DBProvider spCheckIsCreatedForZhouqi EXECUTE_DB Error:{0}", strError);
            }
            var IDList = TableToList_E.ToList<UserID>(ds.Tables[0]);
            if (IDList.Count > 0 && IDList != null)
            {
                ID = IDList[0].ID;
            }
            return ID > 0;
        }
        public Task<bool> Update(EmailEntity entity, out string s)
        {
            bool bResult = true;
            if (entity.CRoomIDs != "" && entity.CRoomIDs != null)
            {
                string[] arrStr = entity.CRoomIDs.Split(',');//按逗号截取  
                                                             //第一个为主会议室

                entity.CRoomID = Convert.ToInt32(arrStr[0]);
                ArrayList list = new ArrayList(arrStr);
                list.RemoveAt(0);
                entity.CRoomIDs = string.Join(",", (string[])list.ToArray(typeof(string)));
            }
            SqlParameter[] sqlParametersmeet = new SqlParameter[] {
                        //new SqlParameter("@ID",entity.CInfoID),
                  new SqlParameter("@CRoomID",entity.CRoomID),
                  new SqlParameter("@CRoomIDs",entity.CRoomIDs),
                  new SqlParameter("@ParticipantIDs",entity.ParticipantIDs),
                  new SqlParameter("@ConferenceTheme",entity.Subject),
                  new SqlParameter("@BeginTime",entity.Start),
                  new SqlParameter("@EndTime",entity.End),
                  new SqlParameter("@TimeLength",entity.timelength),
                  new SqlParameter("@Coordinator",entity.CreateID),
                  new SqlParameter("@HostPerson",entity.CreateID),
                  new SqlParameter("@MinutesPerson",entity.CreateID),
                  new SqlParameter("@Outsiders",""),
                  new SqlParameter("@ConferenceRemark",""),
                   new SqlParameter("@State",entity.state),
                   new SqlParameter("@GroupIDs",""),
                                 new SqlParameter("@ExchangeItemId",entity.ID),
                                 new SqlParameter("@MasterItemId",entity.itemId)
                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);
            if (!_db.ExcuteByTransaction(parasmeet, "spUpdateConferenceInfo", out string strError))
            {
                bResult = false;
                s = string.Format("DBProvider spUpdateConferenceInfo EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                s = string.Empty;
            }
            return Task.FromResult(bResult);
        }

        public int GetUserID(string Mail)
        {
            int ID = 0;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@Mail",Mail),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spGetUserIDByMail", out DataSet ds, out string strError))
            {
                strError = string.Format("DBProvider spGetUserIDByMail EXECUTE_DB Error:{0}", strError);
            }
            var IDList = TableToList_E.ToList<UserID>(ds.Tables[0]);
            if (IDList.Count > 0 && IDList != null)
            {
                ID = IDList[0].ID;
            }
            return ID;
        }

        public RoomNameAndEmail GetUserEmail(int id)
        {
            string Email = string.Empty;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@id",id),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spGetUserMailByID", out DataSet ds, out string strError))
            {

                strError = string.Format("DBProvider spGetUserMailByID EXECUTE_DB Error:{0}", strError);
            }
            var roomList = TableToList_E.ToList<RoomNameAndEmail>(ds.Tables[0]);

            return roomList[0];
        }

        public RoomNameAndEmail GetRoomrMailByID(int id)
        {
            string Email = string.Empty;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@id",id),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spGetRoomrMailByID", out DataSet ds, out string strError))
            {
                strError = string.Format("DBProvider spGetRoomrMailByID EXECUTE_DB Error:{0}", strError);
            }
            var roomList = TableToList_E.ToList<RoomNameAndEmail>(ds.Tables[0]);
            //    var ewsConfig = TableToList_E.ToList<EwsConfigEntity>(ds.Tables[1]);
            return roomList[0];
        }

        public int GetRoomrIDByName(string Name)
        {
            string Email = string.Empty;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@Name",Name),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spGetRoomIDByName", out DataSet ds, out string strError))
            {
                strError = string.Format("DBProvider spGetRoomIDByName EXECUTE_DB Error:{0}", strError);
            }
            var roomList = TableToList_E.ToList<RoomNameAndEmail>(ds.Tables[0]);

            return roomList[0].ID;
        }

        public List<MeetExchangeItemId> GetMeetExchangeItemIdByID(int id)
        {
            string Email = string.Empty;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                            new SqlParameter("@id",id),
                                   };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spGetRoomrExchangeItemIdByID", out DataSet ds, out string strError))
            {
                strError = string.Format("DBProvider spGetRoomrExchangeItemIdByID EXECUTE_DB Error:{0}", strError);
            }
            var exchangeItemId = TableToList_E.ToList<MeetExchangeItemId>(ds.Tables[0]);

            return exchangeItemId;
        }

        public Task<(bool, int)> Cannel(string ItemId)
        {
            bool bResult = true;
            SqlParameter[] sqlParameters = new SqlParameter[] {
                  new SqlParameter("@ExchangeItemId",ItemId),


                };
            CParameters paras = new CParameters();
            paras.AddRange(sqlParameters);
            if (!_db.ExcuteByTransaction(paras, "spDeleteCInfoByItemId", out int ReturnValue, out string strError))
            {
                bResult = false;
                strError = string.Format("DBProvider spDeleteCInfoByItemId EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                strError = string.Empty;
            }
            return Task.FromResult((bResult, ReturnValue));
        }

        public Task<bool> UpdateOccurrence(EmailEntity entity, int isDelete, out string s)
        {
            bool bResult = true;
            if (entity.CRoomIDs != "" && entity.CRoomIDs != null)
            {
                string[] arrStr = entity.CRoomIDs.Split(',');//按逗号截取  
                                                             //第一个为主会议室

                entity.CRoomID = Convert.ToInt32(arrStr[0]);
                ArrayList list = new ArrayList(arrStr);
                list.RemoveAt(0);
                entity.CRoomIDs = string.Join(",", (string[])list.ToArray(typeof(string)));
            }
            SqlParameter[] sqlParametersmeet = new SqlParameter[] {
                   //new SqlParameter("@ID",entity.CInfoID),
                  new SqlParameter("@CRoomID",entity.CRoomID),
                  new SqlParameter("@CRoomIDs",entity.CRoomIDs),
                  new SqlParameter("@ParticipantIDs",entity.ParticipantIDs),
                  new SqlParameter("@ConferenceTheme",entity.Subject),
                  new SqlParameter("@BeginTime",entity.Start),
                  new SqlParameter("@EndTime",entity.End),
                  new SqlParameter("@TimeLength",entity.timelength),
                  new SqlParameter("@HostPerson",entity.CreateID),
                  new SqlParameter("@Coordinator",entity.CreateID),
                  new SqlParameter("@MinutesPerson",entity.CreateID),
                  new SqlParameter("@Outsiders",""),
                  new SqlParameter("@ConferenceRemark",""),
                   new SqlParameter("@State",entity.state),
                   new SqlParameter("@GroupIDs",""),
                   new SqlParameter("@MasterItemId",entity.itemId),
                   new SqlParameter("@IsDelete",isDelete)
                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);
            if (!_db.ExcuteByTransaction(parasmeet, "spUpdateOccurrenceInfo", out string strError))
            {
                bResult = false;
                s = string.Format("DBProvider spUpdateOccurrenceInfo EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                s = string.Empty;
            }
            return Task.FromResult(bResult);
        }

        public Task<bool> InsertZhouQiTemp(EmailEntity entity, out string s)
        {
            bool bResult = true;

            SqlParameter[] sqlParametersmeet = new SqlParameter[] {

                   new SqlParameter("@MasterItemId",entity.itemId),

                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);
            if (!_db.ExcuteByTransaction(parasmeet, "spInsertZhouQiTemp", out string strError))
            {
                bResult = false;
                s = string.Format("DBProvider spInsertZhouQiTemp EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                s = string.Empty;
            }
            return Task.FromResult(bResult);
        }

        public void DeleteOccurrence(EmailEntity entity, int isDelete, out string s)
        {
            var bResult = false;
            SqlParameter[] sqlParametersmeet = new SqlParameter[] {
                  new SqlParameter("@BeginTime",entity.Start),
                   new SqlParameter("@IsDelete",isDelete),
                   new SqlParameter("@ExchangeItemId",entity.ID)
                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);
            if (!_db.ExcuteByTransaction(parasmeet, "spDeleteOccurrenceInfo", out string strError))
            {
                bResult = false;
                s = string.Format("DBProvider spDeleteOccurrenceInfo EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                s = string.Empty;
            }
        }

        public object CannelNotAccept(string calUid)
        {
            throw new NotImplementedException();
        }
        public Task<bool> InsertSingleTemp(EmailEntity entity, out string s)
        {
            bool bResult = true;

            SqlParameter[] sqlParametersmeet = new SqlParameter[] {

                   new SqlParameter("@ExchangeItemId",entity.ID),

                    };
            CParameters parasmeet = new CParameters();
            parasmeet.AddRange(sqlParametersmeet);
            if (!_db.ExcuteByTransaction(parasmeet, "spInsertSingleTemp", out string strError))
            {
                bResult = false;
                s = string.Format("DBProvider spInsertSingleTemp EXECUTE_DB Error:{0}", strError);
            }
            else
            {
                s = string.Empty;
            }
            return Task.FromResult(bResult);
        }
    }

    public static class TableToList_E
    {
        public static List<T> ToList<T>(this DataTable dt)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T s = Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        try
                        {
                            if (!Convert.IsDBNull(item[i]))
                            {
                                object v = null;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                }
                                info.SetValue(s, v, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                        }
                    }
                }
                list.Add(s);
            }
            return list;
        }
    }

    public class UserID
    {
        public int ID { get; set; }
        public string Mail { get; set; }
    }
}
